<template>
	<view class="wx-Logo login">
		<u-popup v-model="isVisible" mode="bottom" height="240px">
			<view class="container">
				<view class="title">
					<text>微信登录</text>
				</view>
				<view class="">
					<view class="choose-avatar-row">
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
							<image class="avatar" :src="showUrl"></image>
						</button>
						<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
							style="display: contents;color: #807E7E;border: none;font-size: 24rpx;text-align: left;">
							<text class="u-button__text">点击选择头像</text>
						</button>
					</view>
					<view class="choose-nickname-row">
						<text>昵称</text>
						<input v-model="nickName" @blur="inputName" type="nickname" placeholder="请输入昵称"
							style="color: #807E7E;" class='codeinput' />
					</view>
				</view>
				<!-- 按钮 -->
				<view class="login-row" style="margin-top: 60rpx;">
					<button @click="close">关闭</button>
					<button :class="{'inactive' : loginDisabled}" @click="login()">登录</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	import beaeUrl from '@/request/request.js'
	export default {
		name: "wx-login-popup",
		data() {
			return {
				isVisible: false,
				showUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0', //                  默认头像
				avatarUrl: '', //
				nickName: '',
				// 控制登录按钮是否可用
				loginDisabled: false,
				phonelogin: true,
				codelogin: false,
				show: true,
				isCheck: '1',
				isCheckEd: false,
				disabled: false,
				phone: '',
				password: '',
				code: '',
				rules: {
					password: {
						rule: /^[0-9a-zA-Z]{1,16}$/,
						msg: "密码应该为1-16位"
					},
					phone: {
						rule: /^1[3456789]\d{9}$/,
						msg: "手机号格式错误"
					},
					code: {
						rule: /^[0-9]{4}$/,
						msg: "请输入4位数字验证码"
					}
				},
				ltype: '',
				text: '获取验证码',
				time: '',
				hasshowfirst: '',
				loginWX: {
					mobile: '',
					nickName: '',
					avatarUrl: ''
				},
				loginPhone: {
					mobile: '',
					code: ''
				},
			};
		},
		props: {
			optins: {
				type: Object,
				default: {}
			},
			showPop: {
				type: Boolean,
				default: false
			},
			mobile: {
				type: String,
				default: ''
			}
		},
		watch: {
			showPop: {
				handler(val) {
					console.log(val, 'va')
					this.isVisible = val
				},
				immediate: true,
				deep: true
			},
			// 只要昵称填写了就可以提交登录
			nickName(newVal) {
				if (newVal) {
					this.loginDisabled = false
				}
			}
		},
		methods: {
			...mapMutations(['searchList']),
			async getSearchList() {
				let res = await searchList()
				this.searchList(res.data)
				let setData = this.$store.state.searchList
				// console.log(res, setData)
			},
			//选择登录方式
			changeway(r) {
				if (r) {
					this.phonelogin = false;
					this.codelogin = true;
				} else {
					this.phonelogin = true;
					this.codelogin = false;
				}
			},
			//验证
			validate(key) {
				let bool = true;
				if (!this.rules[key].rule.test(this[key])) {
					//提示信息
					uni.showToast({
						title: this.rules[key].msg,
						icon: 'none'
					})
					//取反
					bool = false;
					return false;
				}
				return bool;
			},
			//获取验证码
			async get_code() {
				if (this.disabled) {
					return;
				}
				// this.setInterValFunc();//开启倒计时
				// return
				if (!this.validate('phone')) return;
				uni.showLoading({
					title: '发送中',
					mask: true
				});
				uni.request({
					url: `${beaeUrl.apiUrl}/sms/send`,
					data: {
						mobile: this.phone,
						event: 'login'
					},
					method: 'post', //get、post、delete
					success: re => {
						setTimeout(function() {
							uni.hideLoading();
						}, 100);
						if (re.data.code == 1) {
							this.disabled = true;
							this.setInterValFunc(); //开启倒计时
						} else {
							uni.showToast({
								title: re.data.msg,
								icon: "none"
							})
						}
					}
				})
			},
			//倒计时
			setInterValFunc(e) {
				this.time = e || 60;
				this.text = '秒';
				this.setTime = setInterval(() => {
					if (this.time - 1 <= 0) {
						this.time = '';
						this.text = '重新获取';
						if (e) {
							this.text = '获取验证码';
						}
						this.code = '';
						this.disabled = false;
						clearInterval(this.setTime);
						if (uni.getStorageSync('userInfo')) {
							this.text = '获取验证码';
						}
					} else {
						this.time--;
					}
				}, 1000);
			},
			//跳转
			goto(url) {
				uni.navigateTo({
					url: url
				})
			},
			//登录
			login() {
				this.$emit('changeMobile')
				if (this.phonelogin) {
					if (this.getArUrl == '') {
						uni.showToast({
							title: '请上传头像',
							icon: 'none'
						});
						return false;
					}
					if (this.nickName == '') {
						uni.showToast({
							title: '请填写昵称',
							icon: 'none'
						});
						return false;
					}
					let that = this
					wx.login({
						provider: 'weixin',
						success: loginRes => {
							const paramsData = {
								code: loginRes.code,
								avatar: this.avatarUrl,
								nickname: this.nickName,
								// mobile: uni.getStorageSync('mobile'),
							}
							if (uni.getStorageSync('inviter_id')) paramsData.inviter_id = uni.getStorageSync(
								'inviter_id')

							that.$api.wxLogin(paramsData).then(r => {
								uni.showToast({
									title: '登录成功',
									duration: 1500
								})
								uni.removeStorageSync('inviter_id')
								this.close()
								// this.getSearchList()
								uni.setStorageSync('userInfo', r.data.data)
								this.show = false;
								uni.setStorageSync('token', r.data.data.token)
								// this.$emit('update')
								// uni.$emit('hasLogin', true)
								console.log(that.optins, 'that.optins.route')
								if (that.optins.route) {
									// console.log('我进来了')
									const barList = ['pages/tabBar/home/home',
										'pages/tabBar/shop/shop', 'pages/tabBar/order/order',
										'pages/tabBar/my/my'
									]
									const query = that.$utils.objToArray([], that.optins, 'route')
									const url =
										`/${that.optins.route}${query.length > 0 ? '?' + query.join('&') : ''}`
									console.log(query, url, 'urllll')
									barList.includes(that.optins.route) ? uni.switchTab({
										url
									}) : uni.navigateTo({
										url
									})

								} else if (uni.getStorageSync('beInvited')) {
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										})
									}, 1000)
								} else {
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/tabBar/home/home'
										})
									}, 1000)
								}

							})
						}
					})
				} else {
					//手机号验证码登录
					if (!this.validate("code")) return;
					uni.showLoading({
						title: '登录中',
						mask: true
					});
					uni.request({
						url: `${beaeUrl.apiUrl}/user/getWxPhone`,
						data: {
							mobile: this.phone,
							code: this.code
						},
						method: 'post', //get、post、delete
						success: re => {
							uni.hideLoading();
							if (re.data.code == 1) {
								uni.showToast({
									title: '登录成功',
									duration: 1500
								})
								this.getSearchList()
								uni.setStorageSync('userInfo', re.data.data)
								this.show = false;
								uni.setStorageSync('token', re.data.data.token)
								this.$emit('update')
								this.text = '获取验证码';
								this.setInterValFunc(1)
								this.code = '';
								this.disabled = false;
								uni.$emit('hasLogin', true)
							} else {
								uni.showToast({
									title: re.data.msg,
									icon: 'none'
								});
							}
						}
					})
				}

			},
			// 选择头像事件
			async onChooseAvatar(e) {
				console.log(e, 'eee')
				let {
					avatarUrl
				} = e.detail
				// 我这边是把文件上传到云服务器
				let getavatarUrl = await this.uploadFilePromise(avatarUrl)
				this.avatarUrl = getavatarUrl.url
				this.showUrl = getavatarUrl.showUrl
				// console.log(this.avatarUrl,'1',this.showUrl)
			},
			// 上传头像图片到服务器
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${beaeUrl.apiUrl}/common/userUpload`, // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test',
						},
						success: (res) => {
							setTimeout(() => {
								resolve({
									url: JSON.parse(res.data).data.url,
									showUrl: JSON.parse(res.data).data.fullurl,
								})
							}, 1000)
						},
						fail(fails) {
							console.log(fails, 'fail')
						}
					});
				})
			},
			// 昵称输入事件
			inputName(e) {
				const {
					value
				} = e.detail
				this.nickName = value
				// do something
			},
			// 关闭按钮点击事件
			close() {
				this.$emit('update', false)
			},
			// 登录成功后执行
			submit() {
				const userInfo = {
					avatarUrl: this.avatarUrl,
					nickName: this.nickName
				}
				this.$emit('submit', userInfo)
			}
		}
	}
</script>

<style lang="scss" scoped>
	view {
		box-sizing: border-box;
	}

	.form {
		width: 100%;
		height: 100rpx;
		background-color: #F2F2F2;
		/* margin-top:40rpx; */
		/* border-radius: 40rpx; */
		border-bottom: 1px solid #F2F2F2;
	}

	.wx-Logo {}

	.myColor {
		color: #807E7E;
	}

	.desc {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: #807E7E;
		font-size: 24rpx;
		text-align: center;
		margin: 50rpx 0;
	}

	.container {
		// width: 100%;
		// height: 45%;
		// position: absolute;
		// left: 0;
		// bottom: 0;
		padding: 0 20px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;

		.title {
			width: 100%;
			height: 30%;
			font-size: 28rpx;
			font-weight: bold;
			padding-top: 30rpx;
			color: #2f2e2e;
			margin-bottom: 10rpx;

			text:nth-child(2) {
				display: block;
				font-size: 24rpx;
				font-weight: normal;
				margin-top: 20rpx;
				margin-bottom: 20rpx;
			}
		}

		.choose-avatar-row,
		.choose-nickname-row {
			width: 100%;
			height: 20%;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 10px 20px;
			font-size: 24rpx;
			border-bottom: 1px solid #F2F2F2;

			.avatar-wrapper {
				width: 40px;
				height: 40px;
				margin: 0;
				padding: 0;
				margin-right: 33rpx;

				.avatar {
					width: 100%;
					height: 100%;
				}
			}
		}

		.choose-nickname-row {
			border-top: none;

			text {
				width: 45px;
				margin-right: 24rpx;
				color: #807E7E;
				;
			}
		}

		.login-row {
			width: 100%;
			height: 30%;
			padding-top: 0px;
			display: flex;
			margin-bottom: 50px;

			button {
				font-size: 24rpx;
				width: 30%;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				border-color: transparent;
				color: #157DFA;
				background: #FFFFFF;
				;
			}

			button:last-of-type {
				font-size: 24rpx;
				width: 30%;
				height: 40px;
				display: flex;
				align-items: center;
				justify-content: center;
				border-color: transparent;
				color: #fff;
				background: #157DFA;
			}

			.inactive {
				color: #ccc;
			}
		}
	}

	.bg-set {
		position: fixed;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
		z-index: -1;
		background: #FFFFFF;
	}

	.login {
		width: 90%;
		margin: 0 auto;
		height: 30vh;
		// color:#FFFFFF;
	}

	.login .logo {
		margin-top: 100rpx;
		width: 100%;
		height: 300rpx;
		text-align: center;
	}

	.login .logo image {
		width: 200rpx;
		height: 200rpx;
	}

	.login .info {
		width: 100%;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		font-size: 30rpx;
	}

	.login .form {
		width: 100%;
		height: 100rpx;
		background-color: #FFFFFF;
		/* margin-top:40rpx; */
		/* border-radius: 40rpx; */
		border-bottom: 1px solid #F2F2F2;
	}

	.login .form .left {
		width: 100rpx;
		height: 100rpx;
		line-height: 100rpx;
		float: left;
		color: #807E7E;
		text-align: center;
	}

	.login .form .next {
		float: left;
		width: 8px;
		height: 8px;
		border-top: 2px solid #807E7E;
		border-right: 2px solid #807E7E;
		transform: rotate(135deg);
		margin-top: 35rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
	}

	.login .form .right {
		height: 100rpx;
		float: left;
	}

	.login .form .right .logininput {
		width: 90%;
		margin: 0 auto;
		height: 100rpx;
		line-height: 100rpx;
		color: #000000;
		font-size: 26rpx;
	}

	.login .form .input {
		width: 75%;
		margin: 0 auto;
		height: 100rpx;
		line-height: 100rpx;
		color: #000000;
		float: left;
		margin-left: 5%;
		font-size: 26rpx;
	}

	.placeholder {
		font-size: 26rpx;
		color: #807E7E;
		line-height: 60rpx;
	}

	.login .forget {
		text-align: right;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 26rpx;
		color: #000;
	}

	.login .info1 {
		color: #807E7E;
		font-size: 24rpx;
		text-align: left;
		width: 100%;
		height: 100rpx;
		line-height: 100rpx;
	}

	.login .form .codeinput {
		width: 60%;
		margin: 0 auto;
		height: 100rpx;
		line-height: 100rpx;
		color: #000000;
		float: left;
		margin-left: 5%;
		font-size: 26rpx;
	}

	.login .form .huoqu {
		width: 30%;
		height: 100rpx;
		line-height: 100rpx;
		float: right;
		font-size: 26rpx;
		text-align: center;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #0066FF;
	}

	.login .form .huoquzhong {
		width: 30%;
		height: 100rpx;
		line-height: 100rpx;
		float: right;
		font-size: 26rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		text-align: center;
		color: #999999;
	}

	.btn {
		width: 90%;
		margin: 0 auto;
		text-align: center;
		font-size: 26rpx;
	}

	.chonseLogin {
		z-index: 1;
	}

	.btn .button {
		background-color: #ECECEC;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		// color:#ffffff;
		letter-spacing: 10rpx;
	}

	.btn .desc {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		color: #807E7E;
	}

	.btn .isCheckEd {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		// color:#ffffff;
		letter-spacing: 10rpx;
		background-color: #0066ff;
	}

	.footer {
		width: 90%;
		height: 140rpx;
		margin: 0 auto;
		margin-top: 100rpx;

	}

	.footer .desc {
		width: 100%;
		margin: 0 auto;
		height: 80rpx;
		line-height: 80rpx;
		color: #807E7E;
		text-align: center;
		font-size: 26rpx;
	}
</style>